﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Web;
using Glimpse.Core.Extensibility;
using Glimpse.Elmah.Responder.Resources;

namespace Glimpse.Elmah.Responder
{
    [GlimpseHandler]
    public class PagerHandler : IGlimpseHandler
    {
        [ImportMany]
        public IEnumerable<IElmahResource> Resources { get; set; }

        public string ResourceName
        {
            get { return "Pager"; }
        }

        public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest(HttpContextBase contextBase)
        {
            if (contextBase == null)
                return;
			
            var resourceIdentity = contextBase.Request.QueryString["resource"];
            var resource = Resources.SingleOrDefault(r => r.Identity == resourceIdentity);
            if (resource == null)
            {
                throw new InvalidOperationException(string.Format("Invalid resource identity: {0}", resourceIdentity));
            }
			
            var buffer = resource.Data;
			if (buffer == null)
				return;

            var response = contextBase.Response;
            response.AddHeader("Content-Type", resource.Type);
        	response.BinaryWrite(buffer);
        }
    }
}